<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin_node_model extends SDF_Model
{
    var $title = '';
    var $content = '';
    var $date = '';
    private static $admin_node_data = array();
    private static $admin_node_tree = array();
    private static $nodes = array();
    private static $admin_node_all = array();#所有节点列表

    /**
     * 构造函数 初始化数据库操作类
     */
    function __construct()
    {
        $this->load->database();
        parent::__construct();
    }
    private $option = array();
    private $ref = null;

    /**
     * 公用数据更新函数
     * @param $where
     * @param $data
     * @return mixed执行成功返回影响的数量，失败返回FALSE
     */
    public function _update($where,$data){
    	if(isset($data['node_groupid']) and empty($data['node_groupid'])){
    		$data['node_groupid'] = null;
    	}
        $this->db->where($where);
        if($this->db->update($this->_table,$data)){
        	return $this->db->affected_rows();
        }else{
            return false;
        }
    }

    /**
     * 获取废弃节点列表
     * @return array
     */
    public function get_scrap_nodes(){
        $file_node_list = $this->get_file_nodes();
        $node_list = $this->get_admin_node_all();
        $scrap_list = array_diff_key($node_list,$file_node_list);
        return $scrap_list;
    }
    /**
     * 获取新节点列表
     * @return array
     */
    public function get_new_nodes(){
        $file_node_list = $this->get_file_nodes();
        $node_list = $this->get_admin_node_all();
        $new_list = array_diff_key($file_node_list,$node_list);
        return $new_list;
    }

    /**
     * '插入权限节点时。自动分组
     * @param $data
     * @return bool
     */
    public function _insert($data){
        if(isset($data['modules']) and isset($data['controller']) and isset($data['method']) and empty($data['node_groupid'])){
            $this->load->model('admin/admin_node_group_model');
            if($data['method']=='index'){
                $data['status'] = 1;
            }
            $controller_title = empty($data['controller_title'])?$data['title']:$data['controller_title'];
            $data['node_groupid']  = $this->admin_node_group_model->get_group_id($data['modules'],$data['controller'],$controller_title);
            if($this->db->insert('admin_node', $data)){
                return $this->db->insert_id();
            }
        }
        return false;
    }

    /**
     * 权限读取::获取模块列表
     */
    /*private function get_controllers($modules_path){
        $controller = array();
        $this->load->helper('file');
        $files = get_dir_file_info($modules_path);
        if(!is_array($files))return $controller;
        foreach($files as $vo){
            if(is_file($vo['server_path'])){
                $vo['methods'] = $this->get_methods($vo['server_path']);
                if(empty($vo['methods']))continue;

                $doc_comment = $this->ref->getDocComment();
                $doc_comment = str_replace(array('/','*',"\r","\n"),' ',$doc_comment);
                $doc_comment = explode(' ',trim($doc_comment));
                $doc_comment = $doc_comment[0];
                $vo['doc_comment'] = $doc_comment;
                $vo['name'] = basename($vo['name'],".php");
                $controller[]=$vo;
            }
        }
        return $controller;
    }*/

    /**
     * 读取控制器文件里节点列表
     * @return array
     */
    private function get_file_nodes(){
        if(!empty(self::$nodes)){
            return self::$nodes;
        }
        $controllers_files = $this->get_controllers_files();
        foreach($controllers_files as $controllers_file){
            require_once($controllers_file);
            $controller = strtolower(basename($controllers_file,".php"));
            $modules = str_replace(array('/', '.'), '', str_replace(APPPATH.'controllers','',dirname($controllers_file))).'/';
            if(!class_exists(ucfirst($controller))){
                continue;
            }
            $ref = new ReflectionClass(ucfirst($controller));
            foreach($ref->getMethods() as $m_obj){
                $method = $m_obj->getName();
                if($m_obj->isPublic() and $method !='__construct' and $method != '_remap' and $method != 'get_instance'){
                    $remark = $m_obj->getDocComment();
                    $title = $this->get_doc_comment_title($remark);
                    self::$nodes[$modules.$controller.'/'.$method] = array(
                        'modules' =>$modules,
                        'controller' =>$controller,
                        'method' =>$method,
                        'title' =>empty($title)?$method:$title,
                        'controller_title'=>$this->get_doc_comment_title($ref->getDocComment()),
                        'remark'     =>$remark
                    );
                }
            }
            unset($ref);
        }
        return self::$nodes;
    }
    /**
     * 返回注释的第一行的第一段内容
     * @param $doc_comment
     * @return mixed
     */
    private function get_doc_comment_title($doc_comment){
        $doc_comment = explode(' ',trim(str_replace(array('/','*',"\r","\n"),' ',$doc_comment)));
        return $doc_comment[0];
    }
    /**
     * 获取所有控制器文件列表
     * @return array
     */
    private function get_controllers_files(){
        $file_names = array_merge(glob(APPPATH.'controllers/*.php'),glob(APPPATH.'controllers/*/*.php'));
        return $file_names;
    }
    /**
     * 获取权限节点树
     * @param array $where
     * @return array
     */
    /*public function get_admin_node_tree($where=array()){
        $key = serialize($where);
        if(isset(self::$admin_node_tree[$key]))return self::$admin_node_tree[$key];
        $list = $this->_order_by('sort_order','DESC')->_map(array('where'=>$where))->_list();
        if(empty($list))return array();

        $modules = array();
        $controller = array();
        $method = array();
        foreach($list as $vo){
            if($vo['controller'] == '' ){
                $modules[] = $vo;
            }elseif($vo['method']==''){
                $controller[] = $vo;
            }else{
                $method[] = $vo;
            }
        }
        foreach($modules as &$mo){
            foreach($controller as &$co){
                foreach($method as &$me){
                    if($me['controller'] == $co['controller'] and $me['modules']==$mo['modules']){
                        $co['son'][$me['id']] = $me;
                    }
                }
                if($mo['modules'] == $co['modules']){
                    $mo['son'][$co['id']] = $co;
                }
            }
        }
        self::$admin_node_tree[$key] = $modules;
        return $modules;
    }*/

    /**
     * 获取所有权限列表
     * @return array
     */
    public function get_admin_node_all(){
        return $this->get_admin_node('all');
    }
    /**
     * 获取所有可显示在左侧菜单的权限节点
     * @return array
     */
    public function get_admin_node_menu(){
        return $this->get_admin_node(1);
    }
    /**
     * @param string $status
     * @return mixed
     */
    private function get_admin_node($status){
        if(isset(self::$admin_node_all[$status])){
            return self::$admin_node_all[$status];
        }
        if($status !=='all'){
            $this->db->where('status',$status);
        }
        $this->db->select('id,modules,controller,method,title,node_groupid,remark');
        $query = $this->db->get('admin_node');
        if(!empty($query)){
            $list = $query->result_array();
            foreach ($list as $v){
                self::$admin_node_all[$status][$v['modules'].$v['controller'].'/'.$v['method']] = $v;
            }
            unset($list);
        }
        return isset(self::$admin_node_all[$status])?self::$admin_node_all[$status]:array();
    }
    /**
     * 获取权限集合
     */
    /*public function result($where){
    	if($where) $this->db->where($where);
    	$this->db->order_by('sort_order','desc');
    	$this->_from('admin_node');
    	$query = $this->db->get();
    	$list = $query->result_array();
        return $list;    	   	
    }*/
    
    /**
     * 获取权限组树集合
     * @return array
     */
    /*public function get_admin_node_group(){
        $list_arr = array();
        $tree = array();
    	$this->_from('admin_node_group');
        $this->db->where('status',1);
        $list = $this->_order_by('id,sort_order','DESC')->_list();
        foreach ($list as $vo) {
        	$vo['title'] = &$vo['name'];	
            $list_arr[$vo['id']] = $vo;
        }
        foreach ($list_arr as $vo) {
            if (isset($list_arr[$vo['pid']])) {
                $list_arr[$vo['pid']]['son'][$vo['id']] = &$list_arr[$vo['id']];
            } else {
                $tree[$vo['id']] = &$list_arr[$vo['id']];
            }
        }        
        return $tree;
    }*/

}